Categories
Node.js Tips

Node.js Tips — Testing Events, Env Variables, and Editing Mongoose Objects

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

How to Load an Image from a URL into a Buffer in Node.js

We can make a request for the image.

Then we can use the Buffer.from method to load it into a buffer.

For instance, we can write:

const response = await axios.get(url,  { responseType: 'arraybuffer' })
const buffer = Buffer.from(response.data, "utf-8")

We use the Axios HTTP client to make a GET request.

To do that, we pass in the URL for the image and set the responseType of the response to 'arraybuffer' .

Then we pass in response.data to the Buffer.from method with the 'utf-8' encoding.

This saves the data to the buffer.

Loading Environment Variables with dotenv

We can load environment variables with the dotenv library.

To do that, we write:

const path = require('path')
require('dotenv').config({ path: path.resolve(__dirname, '../.env') })

We require the dotenv library.

Then we call the config method to set the path of the .env file.

We specified that we move one level up from the current directory to find the .env file.

Read Lines Synchronously from a Text File in Node.js

We can use the readFileSync method to read a text file synchronously.

For example,m we can write:

const fs = require('fs');
const lines = fs.readFileSync(filename, 'utf-8')
  .split('n')
  .filter(Boolean);

We call readFileSync to read the text file’s content.

Then we call split to split the string by the newline character.

Then we call filter with Boolean to remove any lines with empty strings.

This works because empty strings are falsy.

So Boolean will convert them to false.

Parse Filename from URL with Node.js

To get a file name from a URL, we can use the url and path modules.

For instance, we can write:

const url = require("url");
const path = require("path");
const parsed = url.parse("http://example.com:8080/test/foo.txt/?q=100");
console.log(path.basename(parsed.pathname));

We call url.parse to parse the URL into its parts.

Then we can use the basename to get the last part of the URL before the query string, which is 'foo.txt' .

Send Cookies with node-fetch

We can send cookies with node-fetch by setting the cookie header.

For instance, we can write:

fetch('/some/url', {
  headers: {
    accept: '*/*',
    cookie: 'accessToken=1234; userId=1234',
  },
  method: 'GET',
});

We use the fetch function from the library.

The cookie is set in the headers property of the 2nd argument.

The cookie property has the cookie.

Add Properties to an Object Returned from Mongoose

If we want to add properties to an object that’s retrieved from Mongoose, we can either use the lean method or we can call toObject on the returned document.

For instance, we can write:

Item.findById(id).lean().exec((err, doc) => {
  //...
});

Then we can add properties to doc since it’s a plain object.

Or we can write:

Item.findById(id).exec((err, doc) => {
  const obj = doc.toObject();
  //...
});

In the callback, we call doc.toObject() to return a plain object from the document.

Then we can manipulate obj as we wish.

How to Test Node.js Event Emitters with Sinon

We can test event emitters in Sinon by using its spies.

For instance, we can write:

const sinon = require('sinon');
const EventEmitter = require('events').EventEmitter;

describe('EventEmitter', function() {
  describe('#emit()', function() {
    it('should invoke the callback', () => {
      const spy = sinon.spy();
      const emitter = new EventEmitter();
      emitter.on('foo', spy);
      emitter.emit('foo');
      spy.called.should.equal.true;
    })

    it('should pass arguments to the callbacks', () => {
      const spy = sinon.spy();
      const emitter = new EventEmitter();
      emitter.on('foo', spy);
      emitter.emit('foo', 'bar', 'baz');
      sinon.assert.calledOnce(spy);
      sinon.assert.calledWith(spy, 'bar', 'baz');
    })
  })
})

We pass in the spy as the event handler function.

Then we can check if the spy is being called.

If it is, then the event is emitted.

Otherwise, it’s not.

We can check if arguments are called with emit by using calledWith to check them.

Conclusion

We cab load an image as an array buffer to save it to a Node buffer.

The dotenv library can be used to load environment variables in a Node app.

If we want to add properties to the document retrieve from Mongoose, we can use lean or call the toObject method.

We can test for even emitter events with spies.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *